import { useGotoClick } from '../../utils/hooks';
import React, { useCallback, useEffect, useState } from 'react';
import { Button, Card, Form, H3, Input, InputNumber, Justify, Layout, Select } from 'tea-component';
import { Controller, useForm } from 'react-hook-form';
import formUtils, { getStatus, Validator } from '../../utils/form-utils';
import GlossaryGuide from '../../common/components/glossary-guide';
import { ConsumeNode, OrgUser } from '../../common/apis/chains/interface';
import { fetchConsumeNodes, fetchOrgUsers } from '../../common/apis/chains';
import { useChainCreate } from '../../common/apis/chains/hooks';


const { Content } = Layout;
interface IInitialData {
  ChainId: string;
  ChainName: string;
  BlockTxCapacity: number;
  BlockInterval: number;
  TxTimeout: number;
  NodeName: string;
  UserName: string;
  StorageSize: string;
}

export default function ChainNew() {
  const handleBackClick = useGotoClick('/chains');
  return (
    <>
      <Content.Header title="区块链管理/新建区块链" showBackButton onBackButtonClick={handleBackClick} />
      <Content.Body full>
        <Card>
          <Card.Body>
            <Justify className={'content-mb-4n'} />
            <ChainConfig />
          </Card.Body>
        </Card>
      </Content.Body>
    </>
  );
}

function ChainConfig() {
  const goBack = useGotoClick('/chains');
  const {
    control,
    handleSubmit,
    formState: { isValidating, isSubmitted, isValid },
  } = useForm({
    mode: 'onBlur',
    defaultValues: {
      BlockTxCapacity: 100,
      BlockInterval: 10,
      TxTimeout: 600,
      StorageSize: 5,
    } as any,
  });

  const [consums, setConsums] = useState<ConsumeNode[]>([]);
  const [orgUser, setOrgUser] = useState<OrgUser[]>([]);

  const getConsumes = useCallback(() => {
    fetchConsumeNodes().then((res) => {
      setConsums(res.data.Response.GroupList);
    });
  }, []);

  const getOrgUsers = useCallback(() => {
    fetchOrgUsers().then((res) => {
      setOrgUser(res.data.Response.GroupList);
    });
  }, []);

  useEffect(() => {
    getConsumes();
    getOrgUsers();
  }, []);

  const { run } = useChainCreate();

  const submit = async (values: IInitialData) => {
    await run({
      ChainId: values.ChainId,
      ChainName: values.ChainName,
      BlockTxCapacity: values.BlockTxCapacity,
      BlockInterval: values.BlockInterval,
      TxTimeout: values.TxTimeout,
      NodeName: values.NodeName,
      UserName: values.UserName,
      StorageSize: values.StorageSize,
    });
    goBack();
  };

  return (
    <>
      <Justify className={'tea-mt-5n'} left={<H3>基础信息</H3>} />
      <Form className={'tea-mt-5n tea-mb-5n'} layout="fixed" fixedLabelWidth={100}>
        <Controller
          control={control}
          rules={{
            validate: Validator.validateChainId,
          }}
          name="ChainId"
          render={({ field, fieldState }) => (
            <Form.Item
              label={<GlossaryGuide title={'区块链ID'} />}
              required
              status={formUtils.getStatus({
                fieldState,
                isValidating,
                isSubmitted,
              })}
              message={fieldState.error?.message}
            >
              <Input autoComplete="off" placeholder="请输入区块链ID" {...field} />
            </Form.Item>
          )}
        />
        <Controller
          control={control}
          rules={{
            validate: Validator.validateChainName,
          }}
          name="ChainName"
          render={({ field, fieldState }) => (
            <Form.Item
              status={formUtils.getStatus({
                fieldState,
                isValidating,
                isSubmitted,
              })}
              required
              label="区块链名称"
              message={fieldState.error?.message}
            >
              <Input placeholder="请输入区块链名称" {...field} autoComplete="off" />
            </Form.Item>
          )}
        />

        <Controller
          control={control}
          name="BlockTxCapacity"
          render={({ field, fieldState }) => (
            <Form.Item
              required
              status={formUtils.getStatus({
                fieldState,
                isValidating,
                isSubmitted,
              })}
              label={<GlossaryGuide title={'区块最大容量'} />}
              message={fieldState.error?.message}
            >
              <InputNumber
                min={Validator.minBlockTxCapacity}
                max={Validator.maxNumber}
                unit={'笔交易'}
                size={'l'}
                {...field}
              />
            </Form.Item>
          )}
        />
        <Controller
          control={control}
          name="BlockInterval"
          render={({ field, fieldState }) => (
            <Form.Item
              required
              status={formUtils.getStatus({
                fieldState,
                isValidating,
                isSubmitted,
              })}
              label={<GlossaryGuide title={'出块间隔'} />}
            >
              <InputNumber
                min={Validator.minBlockInterval}
                max={Validator.maxNumber}
                unit={'ms'}
                size={'l'}
                {...field}
              />
            </Form.Item>
          )}
        />
        <Controller
          control={control}
          name="TxTimeout"
          render={({ field, fieldState }) => (
            <Form.Item
              required
              status={formUtils.getStatus({
                fieldState,
                isValidating,
                isSubmitted,
              })}
              label={<GlossaryGuide title={'交易过期时长'} />}
            >
              <InputNumber min={Validator.minTxTimeout} max={Validator.maxNumber} unit={'s'} size={'l'} {...field} />
            </Form.Item>
          )}
        />
        <Controller
          name="NodeName"
          control={control}
          rules={{ required: true }}
          render={({ field, fieldState }) => (
            <Form.Item
              label="节点选择"
              required
              status={getStatus({ fieldState, isSubmitted, isValidating })}
              message={fieldState.error?.message}
            >
              <Select
                size={'m'}
                options={consums.map((item) => ({ text: item.NodeName, value: item.NodeName }))}
                {...field}
              />
            </Form.Item>
          )}
        />
        <Controller
          name="UserName"
          control={control}
          rules={{ required: true }}
          render={({ field, fieldState }) => (
            <Form.Item
              label="用户选择"
              required
              status={getStatus({ fieldState, isSubmitted, isValidating })}
              message={fieldState.error?.message}
            >
              <Select
                size={'m'}
                options={orgUser.map((item) => ({ text: item.UserName, value: item.UserName }))}
                {...field}
              />
            </Form.Item>
          )}
        />
        <Controller
          control={control}
          name="StorageSize"
          render={({ field, fieldState }) => (
            <Form.Item
              required
              status={formUtils.getStatus({
                fieldState,
                isValidating,
                isSubmitted,
              })}
              label={<GlossaryGuide title={'存储容量'} />}
              message={fieldState.error?.message}
            >
              <InputNumber
                min={Validator.minStorageSize}
                max={Validator.maxStorageSize}
                defaultValue={5}
                unit={'Gb'}
                size={'l'}
                {...field}
              />
            </Form.Item>
          )}
        />
      </Form>

      <Justify
        className={'tea-mt-5n'}
        left={
          <>
            <Button onClick={goBack}>取消</Button>
            <Button type="primary" onClick={handleSubmit(submit)} disabled={!isValid}>
              创建
            </Button>
          </>
        }
      />
    </>
  );
}
